package com.kancy.vip.pattern.singleton.register;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ContainerSingleton {
    /**
     * 单例容器
     */
    private final static Map<String, Object> ioc = new ConcurrentHashMap();

    public static <T> T getBean(Class<T> clazz){
        return (T)getBean(clazz.getName());
    }
    public static Object getBean(String beanName){
        if(!ioc.containsKey(beanName)){
            synchronized (ioc){
                try {
                    // double check : 防止多个线程进入第一个判断，重新创建对象
                    if(ioc.containsKey(beanName)){
                        return ioc.get(beanName);
                    }
                    Object obj = createBeanInstance(beanName);
                    ioc.put(beanName, obj);
                    return obj;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ioc.get(beanName);
    }

    private static Object createBeanInstance(String beanName)
            throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> aClass = Class.forName(beanName);
        return aClass.newInstance();
    }

}
